import matplotlib
matplotlib.use('TkAgg')  # 或者 'Qt5Agg'
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import numpy as np
import sys
sys.path.append("..")
import d2lzh_pytorch as d2l


#初始化模型参数
def init_params():
    w = torch.randn((num_inputs, 1), requires_grad=True)
    b = torch.zeros(1, requires_grad=True)
    return [w, b]

#定义范数惩罚项
def l2_penalty(w):
    return (w**2).sum() / 2




def fit_and_plot(lambd,ax=None):
    w, b = init_params()
    train_ls, test_ls = [], []
    for _ in range(num_epochs):
        for X, y in train_iter:
            # 添加了L2范数惩罚项
            l = loss(net(X, w, b), y) + lambd * l2_penalty(w)
            l = l.sum()

            if w.grad is not None:
                w.grad.data.zero_()
                b.grad.data.zero_()
            l.backward()
            d2l.sgd([w, b], lr, batch_size)
        train_ls.append(loss(net(train_features, w, b), train_labels).mean().item())
        test_ls.append(loss(net(test_features, w, b), test_labels).mean().item())
    #d2l.semilogy(range(1, num_epochs + 1), train_ls, 'epochs', 'loss', range(1, num_epochs + 1), test_ls,['train', 'test'])
    #当需要对比图时使用这个

    if ax is None:
        ax = plt.gca()  # 获取当前的坐标轴

    ax.plot(range(1, num_epochs + 1), train_ls, label='train', color='blue')
    ax.plot(range(1, num_epochs + 1), test_ls, label='test', color='red')
    ax.set_xlabel('epochs')
    ax.set_ylabel('loss')
    ax.legend()
    ax.set_title(f"L2 Regularization (lambda={lambd})")
    ax.grid(True)
    print('L2 norm of w:', w.norm().item())




n_train, n_test, num_inputs = 20, 100, 200
true_w, true_b = torch.ones(num_inputs, 1) * 0.01, 0.05
features = torch.randn((n_train + n_test, num_inputs))
labels = torch.matmul(features, true_w) + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
train_features, test_features = features[:n_train, :], features[n_train:, :]
train_labels, test_labels = labels[:n_train], labels[n_train:]

# 定义训练与测试
batch_size, num_epochs, lr = 1, 100, 0.003
net, loss = d2l.linreg, d2l.squared_loss
dataset = torch.utils.data.TensorDataset(train_features, train_labels)
train_iter = torch.utils.data.DataLoader(dataset, batch_size, shuffle=True)


# 创建 1 行 2 列的子图，返回 Figure 和 Axes 对象
fig, ax = plt.subplots(1, 2, figsize=(14, 6))
# 观察过拟合现象 (lambda=0)，将图绘制到第一个子图 (ax[0])
fit_and_plot(lambd=0, ax=ax[0])
# 使用权重衰减 (lambda=3)，将图绘制到第二个子图 (ax[1])
fit_and_plot(lambd=3, ax=ax[1])
# 自动调整布局，避免重叠
plt.tight_layout()
# 显示图形
plt.show()


